package br.dcc.ufmg.persistence;

import java.sql.ResultSet;
import java.sql.Statement;

import br.dcc.ufmg.xml.Metrics.Metric.Values.Value;

public class MetricDAO {

	public boolean isInserted(String id) throws Exception {
		boolean inserted = false;
		String sql = "SELECT id, description FROM metric where id = '" + id
				+ "'";
		Statement stmt = HSQLDBConnection.getConnection().createStatement();
		ResultSet rs = stmt.executeQuery(sql);
		if (rs != null && rs.next()) {
			inserted = true;
		}
		return inserted;
	}

	public void insertMetric(String id, String description) throws Exception {
		String sql = "INSERT INTO metric (id, description) VALUES ('" + id
				+ "', '" + description + "');";
		Statement stmt = HSQLDBConnection.getConnection().createStatement();
		stmt.execute(sql);
		stmt.close();
	}

	public void insertMeasurement(String metric, String source, String per)
			throws Exception {
		String sql = "INSERT INTO measurement (metric_id, source_id, per) VALUES ('"
				+ metric + "', '" + source + "', '" + per + "');";
		Statement stmt = HSQLDBConnection.getConnection().createStatement();
		stmt.execute(sql);
		stmt.close();
	}

	public void insertMeasure(String idMetrica, String idSource, Float value)
			throws Exception {
		String sql = "INSERT INTO measure (metric_id, source_id, value) VALUES ('"
				+ idMetrica + "', '" + idSource + "', " + value + ");";
		Statement stmt = HSQLDBConnection.getConnection().createStatement();
		stmt.execute(sql);
		stmt.close();
	}

	public void insertMeasure(String idMetrica, String idSource, Value value)
			throws Exception {
		String sql = "INSERT INTO measure (metric_id, source_id, name, source, package, value) VALUES ('"
				+ idMetrica
				+ "', '"
				+ idSource
				+ "', "
				+ (value.getName() != null ? ("'" + value.getName() + "'")
						: "null")
				+ ", "
				+ (value.getSource() != null ? ("'" + value.getSource() + "'")
						: "null")
				+ ", "
				+ (value.getPackage() != null ? ("'" + value.getPackage() + "'")
						: "null")
				+ ", "
				+ value.getValue().replaceAll(",", ".") + ");";
		Statement stmt = HSQLDBConnection.getConnection().createStatement();
		System.out.println(sql);
		stmt.execute(sql);
		stmt.close();
	}

	public void insertSource(String scope, String system) throws Exception {
		String sql = "INSERT INTO source (scope, system) VALUES ('" + scope
				+ "', '" + system + "')";
		Statement stmt = HSQLDBConnection.getConnection().createStatement();
		stmt.execute(sql);
		stmt.close();
	}
	
}
